<template>
  <div class="dashboard-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>仪表盘</h1>
    </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-title">总供应商数</div>
            <div class="stat-value">{{ stats.supplierCount }}</div>
            <div class="stat-meta">
              <span class="trend up"><el-icon><CaretTop /></el-icon> {{ stats.supplierGrowth }}%</span>
              <span class="compared">较上月</span>
            </div>
          </div>
          <div class="stat-icon bg-primary"><el-icon><UserFilled /></el-icon></div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-title">本月订单数</div>
            <div class="stat-value">{{ stats.monthlyOrderCount }}</div>
            <div class="stat-meta">
              <span class="trend up"><el-icon><CaretTop /></el-icon> {{ stats.orderGrowth }}%</span>
              <span class="compared">较上月</span>
            </div>
          </div>
          <div class="stat-icon bg-success"><el-icon><ShoppingCart /></el-icon></div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-title">本月交易额</div>
            <div class="stat-value">{{ stats.monthlyAmount | formatCurrency }}</div>
            <div class="stat-meta">
              <span class="trend up"><el-icon><CaretTop /></el-icon> {{ stats.amountGrowth }}%</span>
              <span class="compared">较上月</span>
            </div>
          </div>
          <div class="stat-icon bg-warning"><el-icon><Money /></el-icon></div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-title">待处理订单</div>
            <div class="stat-value">{{ stats.pendingOrders }}</div>
            <div class="stat-meta">
              <span class="trend down"><el-icon><CaretBottom /></el-icon> {{ stats.pendingOrderDrop }}%</span>
              <span class="compared">较昨日</span>
            </div>
          </div>
          <div class="stat-icon bg-danger"><el-icon><Bell /></el-icon></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表和列表区域 -->
    <el-row :gutter="20" class="content-row">
      <!-- 销售趋势图表 -->
      <el-col :span="16">
        <el-card class="content-card">
          <div class="card-header">
            <h2>销售趋势</h2>
            <el-select v-model="chartRange" size="small" @change="handleChartRangeChange">
              <el-option label="近7天" value="7"></el-option>
              <el-option label="近30天" value="30"></el-option>
              <el-option label="近90天" value="90"></el-option>
              <el-option label="今年" value="year"></el-option>
            </el-select>
          </div>
          <div class="chart-container">
            <el-loading v-loading="chartLoading" element-loading-text="加载中...">
              <echarts :option="chartOption" class="chart" ref="chartRef"></echarts>
            </el-loading>
          </div>
        </el-card>
      </el-col>

      <!-- 最近订单列表 -->
      <el-col :span="8">
        <el-card class="content-card">
          <div class="card-header">
            <h2>最近订单</h2>
            <el-button type="text" size="small" @click="handleViewAllOrders">查看全部</el-button>
          </div>
          <div class="order-list-container">
            <el-loading v-loading="orderListLoading" element-loading-text="加载中...">
              <el-table
                :data="recentOrders"
                size="small"
                border
                highlight-current-row
                @row-click="handleOrderRowClick"
              >
                <el-table-column prop="orderNo" label="订单号" min-width="140" show-overflow-tooltip></el-table-column>
                <el-table-column prop="supplierName" label="供应商" min-width="100" show-overflow-tooltip></el-table-column>
                <el-table-column prop="totalAmount" label="金额" min-width="90" align="right">
                  <template #default="scope">{{ scope.row.totalAmount | formatCurrency }}</template>
                </el-table-column>
                <el-table-column prop="status" label="状态" min-width="80">
                  <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </el-loading>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速操作和待办事项区域 -->
    <el-row :gutter="20" class="content-row">
      <!-- 快速操作 -->
      <el-col :span="8">
        <el-card class="content-card">
          <div class="card-header">
            <h2>快速操作</h2>
          </div>
          <div class="quick-actions">
            <el-button type="primary" class="action-btn" @click="handleAddSupplier">
              <el-icon><Plus /></el-icon> 新增供应商
            </el-button>
            <el-button type="success" class="action-btn" @click="handleSyncOrders">
              <el-icon><Refresh /></el-icon> 同步订单
            </el-button>
            <el-button type="info" class="action-btn" @click="handleImportData">
              <el-icon><Upload /></el-icon> 导入数据
            </el-button>
            <el-button type="warning" class="action-btn" @click="handleSystemSettings">
              <el-icon><Setting /></el-icon> 系统设置
            </el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 待办事项 -->
      <el-col :span="16">
        <el-card class="content-card">
          <div class="card-header">
            <h2>待办事项</h2>
            <el-button type="text" size="small" @click="handleAddTodo">
              <el-icon><CirclePlus /></el-icon> 添加
            </el-button>
          </div>
          <div class="todo-list-container">
            <el-loading v-loading="todoListLoading" element-loading-text="加载中...">
              <el-list class="todo-list">
                <el-list-item v-for="(todo, index) in todoList" :key="index" class="todo-item">
                  <el-checkbox v-model="todo.completed" @change="handleTodoChange(todo, index)"></el-checkbox>
                  <span :class="{ 'completed': todo.completed }">{{ todo.content }}</span>
                  <div class="todo-meta">
                    <span class="due-time">{{ todo.dueTime }}</span>
                    <el-button type="text" size="small" icon="Delete" @click="handleDeleteTodo(index)"></el-button>
                  </div>
                </el-list-item>
              </el-list>
              <div class="empty-tip" v-if="todoList.length === 0">暂无待办事项</div>
            </el-loading>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import {
  UserFilled,
  ShoppingCart,
  Money,
  Bell,
  CaretTop,
  CaretBottom,
  Plus,
  Refresh,
  Upload,
  Setting,
  CirclePlus,
  Delete
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 定义订单状态类型
type OrderStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6;

// 定义订单接口
interface OrderItem {
  id: string;
  orderNo: string;
  supplierName: string;
  totalAmount: number;
  status: OrderStatus;
  createTime: string;
}

// 定义待办事项接口
interface TodoItem {
  completed: boolean;
  content: string;
  dueTime: string;
}

// 状态管理
const router = useRouter();
const chartRef = ref<HTMLDivElement | null>(null);
const chartInstance = ref<echarts.ECharts | null>(null);
const chartLoading = ref(true);
const orderListLoading = ref(true);
const todoListLoading = ref(true);
const chartRange = ref('30');

// 统计数据
const stats = reactive({
  supplierCount: 0,
  supplierGrowth: 0,
  monthlyOrderCount: 0,
  orderGrowth: 0,
  monthlyAmount: 0,
  amountGrowth: 0,
  pendingOrders: 0,
  pendingOrderDrop: 0
});

// 图表配置
const chartOption = ref<echarts.EChartOption>({});

// 最近订单列表
const recentOrders = ref<OrderItem[]>([]);

// 待办事项列表
const todoList = ref<TodoItem[]>([]);

// 格式化金额过滤器
const formatCurrency = (value: number) => {
  return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(value);
};

// 获取订单状态文本
const getStatusText = (status: OrderStatus): string => {
  const statusMap = {
    0: '待确认',
    1: '已确认',
    2: '已发货',
    3: '已收货',
    4: '已完成',
    5: '已取消',
    6: '异常'
  };
  return statusMap[status] || '未知';
};

// 获取订单状态标签类型
const getStatusTagType = (status: OrderStatus): string => {
  const typeMap = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'processing',
    4: 'success',
    5: 'danger',
    6: 'warning'
  };
  return typeMap[status] || 'default';
};

// 查看全部订单
const handleViewAllOrders = () => {
  router.push({ name: 'OrderList' });
};

// 点击订单行
const handleOrderRowClick = (row: OrderItem) => {
  router.push({ name: 'OrderDetail', params: { id: row.id } });
};

// 图表时间范围变化
const handleChartRangeChange = (range: string) => {
  // 更新图表数据
  chartLoading.value = true;
  setTimeout(() => {
    generateChartData(range);
    chartLoading.value = false;
  }, 800);
};

// 新增供应商
const handleAddSupplier = () => {
  router.push({ name: 'SupplierAdd' });
};

// 同步订单
const handleSyncOrders = async () => {
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1200));
    ElMessage.success('订单同步成功');
    // 刷新订单列表
    fetchRecentOrders();
  } catch (error) {
    ElMessage.error('订单同步失败');
    console.error('订单同步失败:', error);
  }
};

// 导入数据
const handleImportData = () => {
  ElMessage.info('导入功能开发中...');
};

// 系统设置
const handleSystemSettings = () => {
  ElMessage.info('系统设置页面开发中...');
};

// 添加待办事项
const handleAddTodo = async () => {
  try {
    const inputResult = await ElMessageBox.prompt('请输入待办事项内容', '添加待办事项', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入待办事项'
    });

    const content = inputResult.value.trim();
    if (!content) {
      ElMessage.warning('待办事项内容不能为空');
      return;
    }

    // 添加新的待办事项
    todoList.value.unshift({
      completed: false,
      content,
      dueTime: new Date().toISOString().slice(0, 10)
    });

    ElMessage.success('待办事项添加成功');
  } catch (error) {
    // 用户取消操作
  }
};

// 待办事项状态变更
const handleTodoChange = (todo: TodoItem, index: number) => {
  todo.completed = !todo.completed;
  ElMessage.success(todo.completed ? '标记完成成功' : '标记未完成成功');
};

// 删除待办事项
const handleDeleteTodo = async (index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除此待办事项吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    todoList.value.splice(index, 1);
    ElMessage.success('待办事项删除成功');
  } catch (error) {
    // 用户取消操作
  }
};

// 生成统计数据
const generateStatsData = () => {
  stats.supplierCount = Math.floor(Math.random() * 200) + 300;
  stats.supplierGrowth = Number((Math.random() * 10 + 5).toFixed(1));
  stats.monthlyOrderCount = Math.floor(Math.random() * 100) + 200;
  stats.orderGrowth = Number((Math.random() * 15 + 8).toFixed(1));
  stats.monthlyAmount = Math.floor(Math.random() * 1000000) + 5000000;
  stats.amountGrowth = Number((Math.random() * 20 + 10).toFixed(1));
  stats.pendingOrders = Math.floor(Math.random() * 30) + 10;
  stats.pendingOrderDrop = Number((Math.random() * 5 + 2).toFixed(1));
};

// 生成图表数据
const generateChartData = (range: string) => {
  let days = 30;
  if (range === '7') days = 7;
  else if (range === '90') days = 90;
  else if (range === 'year') days = 365;

  // 生成日期标签
  const dates = [];
  const amounts = [];
  const orders = [];

  for (let i = days - 1; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(date.toISOString().slice(5, 10)); // MM-DD

    // 生成随机金额和订单数
    const baseAmount = range === 'year' ? 100000 : 50000;
    const amount = Math.floor(Math.random() * baseAmount) + baseAmount * 0.5;
    amounts.push(amount);

    const orderCount = Math.floor(Math.random() * 10) + 5;
    orders.push(orderCount);
  }

  // 设置图表配置
  chartOption.value = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['交易额', '订单数'],
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: dates,
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          interval: range === '30' ? 4 : (range === '90' ? 9 : (range === 'year' ? 30 : 0))
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '交易额',
        min: 0,
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      {
        type: 'value',
        name: '订单数',
        min: 0,
        axisLabel: {
          formatter: '{value} 单'
        }
      }
    ],
    series: [
      {
        name: '交易额',
        type: 'bar',
        data: amounts,
        itemStyle: {
          color: '#409EFF'
        },
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        data: orders,
        itemStyle: {
          color: '#E6A23C'
        },
        lineStyle: {
          color: '#E6A23C'
        },
        emphasis: {
          focus: 'series'
        }
      }
    ]
  };

  // 更新图表
  if (chartInstance.value) {
    chartInstance.value.setOption(chartOption.value);
  }
};

// 获取最近订单
const fetchRecentOrders = () => {
  orderListLoading.value = true;
  try {
    // 模拟API请求
    setTimeout(() => {
      // 生成模拟数据
      const mockData: OrderItem[] = Array.from({ length: 5 }, (_, i) => ({
        id: `recent-${i + 1}`,
        orderNo: `ZCY${Date.now() - i * 10000}`,
        supplierName: `供应商${Math.floor(Math.random() * 1000) + 1}`,
        totalAmount: Math.floor(Math.random() * 100000) + 1000,
        status: Math.floor(Math.random() * 4) as OrderStatus,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' ')
      }));

      recentOrders.value = mockData;
      orderListLoading.value = false;
    }, 800);
  } catch (error) {
    ElMessage.error('获取最近订单失败');
    console.error('获取最近订单失败:', error);
    orderListLoading.value = false;
  }
};

// 获取待办事项
const fetchTodoList = () => {
  todoListLoading.value = true;
  try {
    // 模拟API请求
    setTimeout(() => {
      // 生成模拟数据
      const mockData: TodoItem[] = [
        {
          completed: false,
          content: '审核供应商资质',
          dueTime: new Date().toISOString().slice(0, 10)
        },
        {
          completed: true,
          content: '处理异常订单',
          dueTime: new Date().toISOString().slice(0, 10)
        },
        {
          completed: false,
          content: '更新产品价格',
          dueTime: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10)
        },
        {
          completed: false,
          content: '准备月度报表',
          dueTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10)
        }
      ];

      todoList.value = mockData;
      todoListLoading.value = false;
    }, 600);
  } catch (error) {
    ElMessage.error('获取待办事项失败');
    console.error('获取待办事项失败:', error);
    todoListLoading.value = false;
  }
};

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance.value = echarts.init(chartRef.value);
    generateChartData(chartRange.value);

    // 窗口大小变化时重绘图表
    window.addEventListener('resize', () => {
      chartInstance.value?.resize();
    });
  }
};

// 页面加载时获取数据
onMounted(() => {
  // 生成统计数据
  generateStatsData();

  // 获取最近订单
  fetchRecentOrders();

  // 获取待办事项
  fetchTodoList();

  // 初始化图表
  nextTick(() => {
    initChart();
    chartLoading.value = false;
  });

  // 监听窗口大小变化，用于响应式布局
  window.addEventListener('resize', () => {
    chartInstance.value?.resize();
  });
});
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 0 20px;
}

.page-header {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  height: 140px;
  transition: all 0.3s ease;
}

.stat-content {
  padding: 15px 15px 15px 20px;
}

.stat-title {
  color: #909399;
  font-size: 14px;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-meta {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.trend {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.up {
  color: #67C23A;
}

.down {
  color: #F56C6C;
}

.compared {
  color: #909399;
}

.stat-icon {
  position: absolute;
  top: 0;
  right: 0;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.bg-primary {
  background: linear-gradient(135deg, #409EFF 0%, #6AAFFF 100%);
}

.bg-success {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
}

.bg-warning {
  background: linear-gradient(135deg, #E6A23C 0%, #F3B760 100%);
}

.bg-danger {
  background: linear-gradient(135deg, #F56C6C 0%, #F88A8A 100%);
}

.content-row {
  margin-bottom: 20px;
}

.content-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.chart-container {
  height: 350px;
}

.chart {
  width: 100%;
  height: 100%;
}

.order-list-container {
  max-height: 350px;
  overflow-y: auto;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  padding: 10px;
}

.action-btn {
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.todo-list-container {
  max-height: 350px;
  overflow-y: auto;
}

.todo-list {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.todo-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #EBEEF5;
  &:last-child {
    border-bottom: none;
  }
}

.todo-item .el-checkbox {
  margin-right: 10px;
}

.todo-item .completed {
  text-decoration: line-through;
  color: #909399;
}

.todo-meta {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.due-time {
  font-size: 12px;
  color: #909399;
  margin-right: 10px;
}

.empty-tip {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

/* 适配小屏幕 */
@media (max-width: 1024px) {
  .el-col {
    &.md-16,
    &.md-8 {
      flex: 0 0 100%;
      max-width: 100%;
    }
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 0 10px;
  }

  .el-col {
    &.lg-6 {
      flex: 0 0 50%;
      max-width: 50%;
    }
  }

  .quick-actions {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .el-col {
    &.lg-6 {
      flex: 0 0 100%;
      max-width: 100%;
    }
  }
}
</style>